const crypto = require('crypto');
const path = require('path');
const fs = require('fs');

// 生成MD5哈希
const generateMD5 = (data) => {
  return crypto.createHash('md5').update(data).digest('hex');
};

// 生成随机文件名（使用安全ASCII，避免原始中文/特殊字符带来URL兼容问题）
const generateRandomFilename = (originalname) => {
  const ext = path.extname(originalname);
  const timestamp = Date.now();
  const randomStr = Math.random().toString(36).substring(2, 10);
  return `${timestamp}_${randomStr}${ext}`;
};

// 确保目录存在
const ensureDirExists = (dirPath) => {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
};

// 删除文件
const deleteFile = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.unlink(filePath, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
};

// 验证管理员权限
const verifyAdmin = (req) => {
  const adminKey = req.headers['x-admin-key'];
  const expectedKey = process.env.ADMIN_KEY || 'default_admin_key';
  return adminKey === expectedKey;
};

// 参数验证工具
const validateRequiredFields = (obj, requiredFields) => {
  const missingFields = [];
  
  requiredFields.forEach(field => {
    if (!obj[field] && obj[field] !== 0) {
      missingFields.push(field);
    }
  });
  
  if (missingFields.length > 0) {
    throw new Error(`缺少必要参数: ${missingFields.join(', ')}`);
  }
  
  return true;
};

module.exports = {
  generateMD5,
  // 计算文件MD5（流式，适合大文件）
  hashFile: (filePath) => {
    return new Promise((resolve, reject) => {
      const hash = crypto.createHash('md5');
      const stream = fs.createReadStream(filePath);
      stream.on('data', (chunk) => hash.update(chunk));
      stream.on('end', () => resolve(hash.digest('hex')));
      stream.on('error', reject);
    });
  },
  generateRandomFilename,
  ensureDirExists,
  deleteFile,
  verifyAdmin,
  validateRequiredFields
};